<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-receiveAddressValue>
              <el-input
                v-model="formInfo.data.receiveAddressValue"
                class="not-br not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择收货地址"
              >
                <template #append>
                  <el-icon @click="openReceiveAddressWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-deptName>
              <el-input
                v-if="purchType === 0"
                v-model="formInfo.data.deptName"
                disabled
              ></el-input>
              <el-input
                v-else-if="purchType !== 0"
                v-model="formInfo.data.deptName"
                class="not-br not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
              >
                <template #append>
                  <el-icon @click="openDeptNameWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
          <div class="model-tips">
            (证照：<span>近效期</span>
            <span class="model-tips-nearly"></span>
          </div>
          <div class="model-tips">
            <span>过期</span>
            <span class="model-tips-expire"></span>)
          </div>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct()"
                >删除产品</el-button
              >
            </template>
          </page-filter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :api="tableInfo.api"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="99999999"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <p>{{ scope.row.price }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </template>
              </page-table>
            </el-form>
          </div>

          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            :table-key="productInfo.tableKey"
            :show-price="productInfo.priceShow"
            @callback="selectProduct"
          />

          <select-supplier
            v-if="supplierInfo.visible"
            :api="getSupplierProductPage"
            :check-box="false"
            :highlight-row="true"
            v-model:show-dialog="supplierInfo.visible"
            :query="supplierInfo.query"
            @callback="selectSupplierCallback"
          />

          <select-receive-address
            v-if="selectReceiveAddressInfo.visible"
            v-model:show-dialog="selectReceiveAddressInfo.visible"
            :query="selectReceiveAddressInfo.query"
            :check-box="false"
            :highlight-row="true"
            @callback="selectReceiveAddressCallback"
          />
        </div>
      </div>
    </NewFullScreen>
    <select-dept
      v-if="deptInfo.visible"
      v-model:showDialog="deptInfo.visible"
      :query="deptInfo.query"
      @callback="selectDeptCallback"
      :checkBox="false"
      :highlightRow="true"
    />
    <SelectContract
      v-if="contractInfo.visible"
      v-model:showDialog="contractInfo.visible"
      :checkBox="true"
      :query="contractInfo.query"
      :data="contractInfo.data"
      :changeContract="contractInfo.changeContract"
      :highlightRow="true"
      :saveEmpty="false"
      @callback="selectContractCallBack"
    />
  </div>
</template>

<script setup name="purchOrderCheckApplication">
import SelectContract from './selectContract'
import {
  getPurchApplicationDetailAll,
  frontPurchOrderByApplicationDetail,
  frontPurchOrderByApplicationOrder,
  purchOrderById,
  getPurchOrderDetailAll,
  createPurchOrderFromApplication,
  applicationSummaryDetailAddProduct,
  applicationDetailAddProduct,
} from '@/api/purch'
import {
  getSupplierProductPage,
  getCoreSystemConfigGetConfigValue,
} from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import _ from 'lodash'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps([
  'visible',
  'title',
  'tableRow',
  'purchApplicationId',
  'orderId',
  'purchApplicationInfo',
  'purchType',
  'purchAccording',
])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref({})
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.deptInfo
      ? proxy.$store.state.user.deptInfo.name
      : '',
    receiveAddressValue: '',
    purchAccording:
      props.purchAccording ||
      proxy.$store.state.permission.systemConfig.purch_according,
  },
  fieldList: [
    {
      label: '申购单号',
      value: 'applicationNo',
      type: 'input',
      disabled: true,
    },
    { label: '部门', value: 'deptName', type: 'slot' },
    { label: '收货地址', value: 'receiveAddressValue', type: 'slot' },
    {
      label: '收货联系人',
      value: 'receiveContacts',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货电话',
      value: 'receivePhone',
      type: 'input',
      disabled: true,
    },
    {
      label: '采购依据',
      value: 'purchAccording',
      type: 'select-model',
      code: 'purch_according',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      className: 'not-br',
    },
  ],
  rules: {
    receiveAddressValue: [
      { required: true, message: '请选择收货地址', trigger: 'change' },
    ],
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      applicationId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      purchType: props.purchType,
      purchAccording: props.purchAccording,
    },
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '切换供应商',
        event: changeSupplier,
        show: true,
      },
      {
        label: '切换合同',
        event: changeContract,
        show: true,
      },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: undefined,
  tableKey: '',
  priceShow: proxy.$permission('pendPurchOrder:price'),
  query: {
    queryMap: {
      productId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      purchAccording: props.purchAccording,
    },
  },
  searchList: [
    {
      type: 'input',
      label: '名称',
      value: 'commonName',
      show: true,
    },
  ],
})
const supplierInfo = ref({
  visible: false,
  query: {
    productId: '',
    supplierIdNotIn: '',
    supplierAuth: 'supplierId',
  },
})
const operateRow = ref({})
const selectReceiveAddressInfo = ref({
  visible: false,
  query: {},
})
const deptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const contractInfo = ref({
  visible: false,
  query: {},
  data: [],
  changeContract: false,
})
const tableKey = ref(
  'purchApplicationToOrder-com.slip.spd.entity.vo.purch.ApplicationDetailVO'
)
const isSpecialEdit = ref(undefined)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canAddProductByContranct = computed(() => {
  return (
    formInfo.value.data.deptId &&
    isSpecialEdit.value !== 1 &&
    parseInt(props.purchAccording) === 2
  )
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections != 0
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  {
    deep: true,
  }
)
watch(
  () => props.purchApplicationId,
  (val) => {
    if (val) {
      frontPurchOrder(val)
    }
  }
)

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '采购数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('pendPurchOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('pendPurchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'cloumn',
      permission: !proxy.$permission('pendPurchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  let changeContract = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换合同',
  ])
  let changeSupplier = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换供应商',
  ])
  changeContract.show = false
  changeSupplier.show = true
  if (parseInt(props.purchAccording) === 2) {
    changeContract.show = true
    changeSupplier.show = false
  }
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
//数量操作模式 qtyOperateMode：0整数模式，2自动算出小数，1手动输入小数
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function openDeptNameWindow() {
  deptInfo.value.visible = true
}
function selectDeptCallback(row) {
  if (row && row.id) {
    formInfo.value.data.deptName = row.name
    formInfo.value.data.deptId = row.id
  }
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.applicationId.value =
        props.purchApplicationId
      getValueList()
      frontPurchOrder(props.purchApplicationId, props.purchType)
      frontPurchDetailList()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
//切换供应商
function changeSupplier(row) {
  operateRow.value = row
  supplierInfo.value.query.productId = row.productId
  supplierInfo.value.query.supplierIdNotIn = row.supplierId
  supplierInfo.value.visible = true
}
function selectSupplierCallback(data) {
  if (data) {
    operateRow.value['supplierId'] = data.supplierId
    operateRow.value['supplierName'] = data.supplierName
    operateRow.value['price'] = data.price
  } else {
    operateRow.value['supplierId'] = ''
    operateRow.value['supplierName'] = ''
    operateRow.value['price'] = ''
  }
}
//根据申购单id获取申购单
function frontPurchOrder(id = undefined, purchType = undefined) {
  if (id && (purchType || purchType === 0)) {
    let data = {
      id: id,
      purchType: purchType,
    }
    frontPurchOrderByApplicationOrder(data).then((resp) => {
      if (resp && resp.success) {
        const data = resp.data
        let newData = {
          deptName: data.deptName,
          deptId: data.deptId,
          applicationId: data.applicationId,
          applicationNo: data.applicationNo,
          receiveProvince: data.receiveProvince,
          receiveCity: data.receiveCity,
          receiveCounty: data.receiveCounty,
          receiveAddress: data.receiveAddress,
          receiveAddressValue:
            data.receiveAddressValue == null ? '' : data.receiveAddressValue,
          receiveContacts: data.receiveContacts,
          receivePhone: data.receivePhone,
          purchType: props.purchType,
        }
        formInfo.value.data = Object.assign({}, formInfo.value.data, newData)
      }
    })
  }
}
function frontPurchDetailList() {
  frontPurchOrderByApplicationDetail(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
//添加产品按钮
function addProduct() {
  const _tableInfo = tableInfo.value
  const idNotIn = _tableInfo.data.map(function (item) {
    return item.productId
  })
  if (props.purchType === 0) {
    productInfo.value.query.queryMap.orderId.value = props.purchApplicationId
    productInfo.value.tableKey =
      'purchApplicationDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
    productInfo.value.api = applicationDetailAddProduct
  } else if (props.purchType === 1) {
    productInfo.value.query.queryMap.orderId.value = props.purchApplicationId
    productInfo.value.tableKey =
      'purchApplicationSummaryDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationSummaryDetailVO'
    productInfo.value.api = applicationSummaryDetailAddProduct
  }
  productInfo.value.query.queryMap.productId.value = idNotIn.toString()
  productInfo.value.query.queryParams.purchAccording = props.purchAccording
  productInfo.value.visible = true
}
//删除产品
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}
//选择产品回调
function selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.productId,
        price: item.defaultSupplierPrice || 0,
        supplierId: item.defaultSupplierId,
        supplierName: item.defaultSupplierName,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.value.visible = true
}
function selectReceiveAddressCallback(data = undefined) {
  const _formInfo = formInfo.value
  if (data) {
    _formInfo.data.receiveAddressValue = data.addressValue
    _formInfo.data.receiveProvince = data.province
    _formInfo.data.receiveCity = data.city
    _formInfo.data.receiveCounty = data.county
    _formInfo.data.receiveAddress = data.address
    _formInfo.data.receiveContacts = data.contacts
    _formInfo.data.receivePhone = data.contactsPhone
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const _formInfo = formInfo.value
    const _tableInfo = tableInfo.value
    if (_tableInfo.data.length <= 0) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '明细列表不能为空',
      })
      return
    }
    const details = _tableInfo.data.map((item) => {
      let smallUnitQty = parseFloat(item.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(item.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(item.largeUnitQty || 0)

      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      item.qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      item.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(item.price)
      )

      return {
        ...item,
        calcQty: calcQty,
        qty: calcQty,
      }
    })
    const data = _formInfo.data
    data.mergeDetails = proxy.$fn.filterBlacklist(details)
    data.purchAccording = props.purchAccording
    const api = createPurchOrderFromApplication
    api(data).then((resp) => {
      if (resp && resp.success) {
        emits('callback', true)
        // proxy.$router.push({name: 'purchOrder'})
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function getPurchOrderById(orderId) {
  purchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
}
function getPurchOrderDetails(orderId) {
  const params = {
    orderId,
  }
  getPurchOrderDetailAll(params).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiff(new Date(), row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff > 0) {
      return 'nearly-row'
    }
  }
  return ''
}
function addProductByContract() {
  contractInfo.value.changeContract = false
  contractInfo.value.data = []
  contractInfo.value.visible = true
}
function selectContractCallBack(data) {
  if (data) {
    if (contractInfo.value.changeContract) {
      tableInfo.value.data[contractInfo.value.selectIndex].contractId = data.id
      tableInfo.value.data[contractInfo.value.selectIndex].quoteContractNo =
        data.orderNo
      tableInfo.value.data[contractInfo.value.selectIndex].price = data.price
      tableInfo.value.data[contractInfo.value.selectIndex].supplierId =
        data.supplierId
      tableInfo.value.data[contractInfo.value.selectIndex].supplierName =
        data.supplierName
      return
    }
    const _data = data.map((item) => {
      item.qty = 0
      item.largeUnitQty = 0
      item.smallUnitQty = 0
      return item
    })
    data.map((item) => {
      const contractItem = _.find(tableInfo.value.data, [
        'productId',
        item.productId,
      ])
      if (!contractItem) tableInfo.value.data.push(item)
    })
  }
}
function changeContract(row, index) {
  //打开切换合同弹窗
  contractInfo.value.visible = true
  contractInfo.value.selectIndex = index
  contractInfo.value.changeContract = true
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
}
</script>
<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
